# from django.shortcuts import render

# Create your views here.
from django.shortcuts import render, redirect
from django.views import View
from django import http
from django.conf import settings
from QQLoginTool.QQtool import OAuthQQ
from django_redis import get_redis_connection

from django.contrib.auth import login,authenticate

from carts.utils import merge_cookie_redis_data
from users.models import User

from .models import OAuthQQUser
from meiduo_mall.utils.my_openid import encode_openid,decode_openid

class QQLoginView(View):
    def get(self,request):
        # 1,创建qq对象
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret= settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state='/')
        # 2.获取qq登录界面
        login_url = oauth_qq.get_qq_url()


        # 3.返回响应
        return http.JsonResponse({
            "login_url":login_url
        })




# 2,获取openid
def response(args):
    pass


class OAuthCallBackView(View):
    def get(self,request):
        # 1,获取参数
        code = request.GET.get("cedo")


        # 2.校验参数
        if not code:
            return http.HttpResponseForbidden("code丢失")

         # 3,获取access_token
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state='/')
        access_token = oauth_qq.get_access_token(code =code)

        # 4，获取openid
        openid = oauth_qq.get_open_id(access_token=access_token)

        # 5.通过openid，查询qq用户
        try:

            qq_user = OAuthQQUser.objest.get(open_id=openid)

        except Exception as e:
            # 5.1 初次授权

            encrypt_openid = encode_openid(openid)
            context = {
                "token":encrypt_openid
            }

            # 5.12返回授权页面
            return render(request,"oauth_callback.html",context=context)

        else:
            # 5.2 q，获取美多用户
            user = qq_user.user

            # 5.3 保持状态
            login(request,user)

            # 5.4 返回响应

            response = redirect('/')
            response.set_cookie("username",user.username)
            response = merge_cookie_redis_data(request, user, response)
            return response



    def post(self,request):
        # 1.获取参数
        encode_openid = request.POST.get("access_token")
        mobile = request.POST.get("mobile")
        password = request.POST.get("password")
        sms_code = request.POST.get("sms_code")


        # 2.检验参数
        # 2.0  解密openid
        openid = decode_openid(encode_openid)

        if not openid:
            return http.HttpResponseForbidden("openid 过期")
        # 2.1 为空参数
        if not all([encode_openid,mobile,sms_code,password]):
            return http.HttpResponseForbidden("参数不全")

        # 2.2 校验短信验证码
        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s" % mobile)

        # 2.3 判断短信验证码是否过期
        if not redis_sms_code:
            return http.HttpResponseForbidden("短信过期")


        # 2.4 判断正确性
        if sms_code != redis_sms_code.decode():
            return http.HttpResponseForbidden("验证码错误")


        # 3.数据入库
        # 3.1 判断账号密码的正确性
        user = authenticate(request,mobile=mobile,password=password)


        # 3.2 判断用户是否存在
        if user:
            # 3.3 创建qq对象用户
            qq_user = OAuthQQUser()

            # 3.4 绑定美多用户和openid
            qq_user.user = user
            qq_user.open_id = openid
            qq_user.save()

            # 3.5状态保持

            login(request,user)

            # 3.6 返回响应
            response = redirect("/")
            response.set_cookie("username",user.username)
            response = merge_cookie_redis_data(request, user, response)
            return response


        else:
            # 4.1 创建美多用户
            user = User.objects.create_user(username=mobile,password=password,mobile=mobile)

            # 4.2 创建qq用户并绑定
            qq_user = OAuthQQUser.objects.create(user=user,open_id=openid)

            # 4.3 状态保持
            login(request.user)

            # 4.4 返回响应
            esponse = redirect("/")
            esponse.set_cookie("username",user.username)
            esponse.set_cookie("username",user.username)
            response = merge_cookie_redis_data(request, user, esponse)
            return response


